<template>
  <div class="app-container">
    <div class="top-right-btn-container">
      <k-button
        v-if="authorityHandle(51)"
        class="top-btn"
        value="添加礼品"
        @click.native="addBabyDialog"
      />
      <k-button
        v-if="authorityHandle(51)"
        class="top-btn"
        value="删除礼品"
        @click.native="deletebaby"
      />
      <div class="boxpricediv">
        <span style="white-space:nowrap;margin-right:10px">抽奖积分：</span>
        <el-input v-model.trim="price" disabled onkeyup="value=value.replace(/[^0-9.]/g,'')" style="width:140px;" />
        <span style="white-space:nowrap;margin-right:10px;margin-left:30px">抽奖折扣：</span>
        <el-input v-model.trim="rebate" disabled onkeyup="value=value.replace(/[^0-9.]/g,'')" style="width:140px;" />
        <span>%</span>
        <span style="white-space:nowrap;margin-right:10px;margin-left:30px">对应箱价：</span>
        <el-input v-model="boxPriceComputed" disabled style="width:140px;" />
        <k-button v-if="authorityHandle(51)" class="top-right-btn" value="完成配置" @click.native="finishSetting" />
      </div>
    </div>
    <!--表格相关 -->
    <el-table
      :key="price + rebate + key"
      :data="tableData"
      style="width: 100%"
      fit
      border
      height="1000"
      :span-method="arraySpanMethod"
      highlight-current-row
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" min-width="30" align="center" />
      <el-table-column type="index" label="序号" fixed width="50" align="center" />
      <el-table-column label="图标" fixed min-width="80" align="center">
        <template slot-scope="scope">
          <el-image
            style="width: 80; height: 80px"
            :src="scope.row.iconUrl"
            :preview-src-list="[scope.row.iconUrl]"
            fit="fill"
          />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="礼品名称" fixed min-width="100" show-overflow-tooltip align="center" />
      <el-table-column v-if="authorityHandle(51)" prop="customPrice" label="自定义价格" sortable min-width="80" align="center">
        <editable-cell v-model="row.customPrice" slot-scope="{row}" :show-input="row.editMode" @keyup.enter.native="upcustomPrice(row)">
          <span slot="content" :style="{'color':row.isUpdate === 2 ? '#3b425d':'#409EFF'}">{{ row.customPrice }}</span>
        </editable-cell>
      </el-table-column>

      <el-table-column v-else prop="customPrice" label="自定义价格" sortable min-width="80" align="center" />
      <el-table-column prop="probability" label="概率" min-width="80" align="center">
        <el-table-column align="center">
          <template slot="header">
            <span>Z </span>
            <el-tooltip placement="top" content="期望价格">
              <i class="el-icon-question" />
            </el-tooltip>
          </template>
          <!-- 期望价格 -->
          <el-table-column width="80" align="center">
            <template #header>
              <span>{{ expectedPriceCal() }} </span>
            </template>
            <editable-cell v-if="false" v-model="row.probability" slot-scope="{row}" :show-input="row.editMode">
              <span slot="content">{{ row.probability }}</span>
            </editable-cell>
            <span v-else>{{ row.probability }}</span>
          </el-table-column>
        </el-table-column>
        <el-table-column prop="name" align="center">
          <template slot="header">
            <span>∑ </span>
            <el-tooltip placement="top" content="概率和">
              <i class="el-icon-question" />
            </el-tooltip>
          </template>
          <!-- 概率和 -->
          <el-table-column width="80" align="center">
            <template #header>
              <span>{{ probilitySumCal() }} </span>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table-column>

      <el-table-column prop="categoryName" label="礼品分类" min-width="80" show-overflow-tooltip align="center" />
      <el-table-column prop="goodsName" label="所在箱子/所属饰品" min-width="100" align="center">
        <!-- <template slot-scope="scope">
          <div v-if="scope.row.dataType === 2">
            <div v-for="(item, index) in scope.row.boxList" :key="index" @click="refreshPage(item.id)">
              <span v-if="item.boxName !== currentBoxName" class="router-link">{{ item.boxName }}</span>
              <span v-else>{{ item.boxName }}</span>
            </div>
          </div>
          <span v-else>{{ scope.row.goodsName }}</span>
        </template> -->
      </el-table-column></el-table>
    <!-- 添加礼品 弹窗 -->
    <k-dialog
      :show-hide.sync="addBaby.showHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="添加礼品"
      class="addBaby-dialog"
      :two-btn="true"
      :close-fun="handleCloseDialog"
      @click="saveBabyData"
    >
      <div class="dialog_container">
        <el-form label-width="auto">
          <!-- <el-form-item label="礼品分类：">
            <el-select v-model="gitfSelectSource" filterable placeholder="请选择" @change="gitfSourceChange">
              <el-option label="平台饰品库" :value="1" />
              <el-option label="礼品管理" :value="2" />
            </el-select>
          </el-form-item> -->
          <el-form-item label="礼品名称：">
            <el-select
              v-model="goodsValueModel"
              multiple
              style="width:400px;"
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="item in goodsResultList"
                :key="item.lineId"
                :label="item.lineName"
                :value="item.lineId"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </k-dialog>
  </div>
</template>

<script>
import { updateGoodsPrice, getPrizeList, getPrizeDetailByIds, getShowProbabilityConfig, setShowProbabilityConfig } from '@/api/task/index'
import { getCategoryList } from '@/api/babylib/platformlib/listdata'
import EditableCell from '@/components/EditableCell'

export default {
  components: { EditableCell },
  data() {
    return {
      goodsValueModel: [],
      goodsResultList: [],
      gitfSelectSource: 1,
      price: -1,
      rebate: -1,
      coinModel: -1,
      currentBoxName: '',
      isCellable: [],
      categoryList: [],
      expectProfit: 0, // 期望利润
      tableData: [], // 表格数据
      listQuery: {
        key: '' // 饰品名称'
      },
      // 全部数据
      resultList: [{
        lineId: -1,
        lineName: ' ',
        lineCheck: false
      }],
      multipleSelection: [],
      addBaby: {
        showHide: false
      },
      key: 1,
      // 添加动态列
      startIndex: 5, // 固定列起始index
      colNums: 1, // 固定概率列个数
      columnIndexArry: [],
      columnStartIndexArry: [],
      columnEndIndexArry: []
    }
  },
  computed: {
    boxPriceComputed: function() {
      return (this.price / this.coinModel).toFixed(2)
    }
  },
  created() {
    this.loadData()
    this.getCategory()
  },
  methods: {
    // 完成配置
    finishSetting() {
      if (this.tableData.length <= 0) {
        this.$message.warning('请添加饰品数据')
        return
      }
      // const sumTemp = this.probilitySumCal()
      // if (Number(sumTemp) !== 100) {
      //   // this.$message.warning('请确保概率和 ∑ 等于100')
      //   this.$message.warning('概率和要等于100,还需要 ' + (100 - Number(sumTemp)).toFixed(2))
      //   return
      // }
      this.$confirm('确定保存当前配置吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const itemList = []
        const queryid = this.$route.query.id
        for (let j = 0; j < this.tableData.length; j++) {
          const id = this.tableData[j].id
          const itemId = this.tableData[j].itemId
          const probability = this.tableData[j].probability
          itemList.push(
            {
              'id': id,
              'itemId': itemId,
              'dataType': 1,
              'probability': probability
            }
          )
        }
        const settingData = {
          boxId: queryid,
          rebate: this.rebate,
          price: this.price,
          itemList
        }
        this.$log(settingData)
        if (itemList.length <= 0) return
        setShowProbabilityConfig(settingData).then(res => {
          if (res.data.success) {
            this.$message.success(res.data.msg)
          } else {
            this.$message.error(res.data.msg)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    // 概率求和
    probilitySumCal() {
      let sum = 0
      this.tableData.map(item => {
        sum += Number(item.probability)
      })
      return sum.toFixed(2)
    },
    // 概率求和
    // probilitySumCal(index, itemIndex) {
    //   let sum = 0
    //   this.tableDataList[itemIndex].map(item => {
    //     sum += Number(item.probabilityList[index])
    //   })
    //   return sum.toFixed(2)
    // },
    // 期望价格
    expectedPriceCal() {
      let sum = 0
      this.tableData.map(item => {
        sum += item.customPrice * item.probability / 100
      })
      const expectedPrice = sum.toFixed(2)
      return expectedPrice
    },
    // 初始化数据
    loadData() {
      const queryid = this.$route.query.id
      this.price = this.$route.query.price
      this.rebate = this.$route.query.rebate
      this.coinModel = this.$route.query.coinModel
      this.$log('queryid', queryid)
      this.refreshPage(queryid)
    },
    addBabyDialog() {
      this.goodsValueModel = []
      const goodsIdList = []
      this.tableData.map(item => {
        goodsIdList.push(item.itemId)
      })
      this.$log(this.tableData, goodsIdList)
      getPrizeList({ alreadyIds: goodsIdList }).then(res => {
        this.addBaby.showHide = true
        this.goodsResultList = res.data
      })
    },
    // // 请求搜索添加饰品的返回列表
    // gitfSourceChange(v) {
    //   this.goodsValueModel = []
    //   const goodsIdList = []
    //   if (v === 1) {
    //     this.tableData.map(item => {
    //       goodsIdList.push(item.id)
    //     })
    //     getGoodsPlatformList({ key: '', alreadyIds: goodsIdList }).then(res => {
    //       this.addBaby.showHide = true
    //       this.goodsResultList = res.data
    //     })
    //   } else {
    //     getPrizeList({ alreadyIds: goodsIdList }).then(res => {
    //       this.addBaby.showHide = true
    //       this.goodsResultList = res.data
    //     })
    //   }
    // },
    // 请求搜索添加饰品的返回列表
    clearReslutList(value) {
      this.resultList = []
    },
    // 选择项发生变化时会触发该事件
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 获取饰品分类
    getCategory() {
      getCategoryList().then(res => {
        const data = res.data
        this.categoryList = data
      })
    },
    // 删除饰品
    deletebaby() {
      const _vue = this
      if (_vue.multipleSelection.length < 1) {
        this.$message.error('请至少选择一条数据进行删除！')
        return
      }
      const selections = _vue.multipleSelection
      this.$confirm('确定删除选中的饰品么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var ids = []
        for (var i = 0; i < selections.length; i++) {
          ids.push(selections[i].id)
        }
        this.tableData = this.tableData.filter(item => !ids.includes(item.id))
        this.setTableSeesionList(this.tableData)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    // 搜索查询事件
    handleFilter() {
      this.loadData()
    },
    upcustomPrice(row) {
      updateGoodsPrice({ id: row.itemId, prizePrice: row.customPrice }).then(res => {
        if (!res.data.success) {
          this.$message.error(res.data.msg)
        }
      })
    },
    // 保存 数据
    saveBabyData() {
      if (this.goodsValueModel.length < 1) {
        this.$message.error('请选择饰品添加！')
        return
      }
      this.$log(this.goodsValueModel)
      getPrizeDetailByIds({ ids: this.goodsValueModel }).then(res => {
        this.$message.success(res.message)
        res.data.map(item => {
          item.probability = 0
        })
        this.tableData.push(...res.data)
        this.setTableSeesionList(this.tableData)
        this.key = this.key + 1
      })
      this.addBaby.showHide = false
    },

    setTableSeesionList(list) {
      sessionStorage.goodsList = JSON.stringify(list.map(row => {
        return {
          ...row,
          probabilityList: [0, 0, 0, 0, 0, 0],
          lineName: row.name,
          lineId: row.itemId
        }
      }))
    },
    handleCloseDialog() {
      this.addBaby.showHide = false
    },
    generateIndexArry() {
      for (let i = 0; i < this.colNums * 2; i++) {
        this.columnIndexArry.push(this.startIndex++)
      }
      this.startIndex = 5
      for (let i = 0; i < this.columnIndexArry.length; i++) {
        if (i % 2 === 0 && i !== this.columnIndexArry.length - 1) {
          this.columnStartIndexArry.push(this.columnIndexArry[i])
        } else {
          this.columnEndIndexArry.push(this.columnIndexArry[i])
        }
      }
    },
    initColumn() {
      this.colNums = 1
      this.columnIndexArry = []
      this.columnStartIndexArry = []
      this.columnEndIndexArry = []
      this.generateIndexArry()
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      for (var item of this.columnStartIndexArry) {
        if (columnIndex === item) {
          return [1, 2]
        } else if (columnIndex === item + 1) {
          return [0, 0]
        }
      }
    },
    // 获取箱子的饰品概率
    refreshPage(id) {
      this.listQuery.id = id
      getShowProbabilityConfig({ boxId: id }).then(res => {
        this.$log(res)
        const data = res.data
        this.tableData = []
        this.tableData = data.map(row => {
          return {
            ...row,
            editMode: false
          }
        })
        // this.price = data.price
        // this.rebate = data.rebate
        // this.currentBoxName = data.boxName
        // this.expectProfit = data.expectProfit
        // sessionStorage.price = this.price
        // sessionStorage.rebate = this.rebate
        // sessionStorage.currentBoxName = data.boxName
        this.setTableSeesionList(data)
        this.initColumn()
      })
    }
  }

}
</script>
<style lang="scss" scoped>
$menuText:#14162E; // 侧边栏字体颜色
$hoverColor:#1D143C;// 鼠标停留主色调浅色
$mainColor:#3b425d;// 主色调
.app-container{
  padding: 30px;
  height:100%;
}
.filter-container {
  margin-bottom: 0px;
  width: 100%;
  height: 48px;
  line-height: 48px;
  .filter-item {
    display: inline-block;
    vertical-align: middle;
    margin-bottom: 10px;
  }
  .kInput{
    position:absolute;
    right: 20px;
  }
  .filter-title{
    height: 48px;
    line-height: 48px;
    font-size: 16px;
    font-weight: 500;
    margin-right: 22px;
    color: #14162E;
  }
  .babyquality {
    margin-right: 20px;
  }
  .babylook,.babycategory{
    margin-right: 20px;
  }
}
.top-btn{
  margin: 30px 0px 30px 0px;
  &:nth-of-type(2){
    margin-left: 20px;
  }
}
.kSelect .el-select .el-input .el-input__inner{
  width: 124px;
}

::v-deep .el-select .el-input.is-focus .el-input__inner {
    border-color: $mainColor;
}
::v-deep .el-input__inner:focus {
    border-color: $mainColor;
}

.top-right-btn-container{
  position: relative;
  .boxpricediv{
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    position: absolute;
    right: 20px;
    top: 30px;
  }
  .top-right-btn{
    margin-left: 80px;
  }
}
.addBaby-dialog{
  ::v-deep .el-dialog__body{
    width: 678px;
  }
  .dialog_container{
    display: flex;
    justify-content: center;
  }
}
.router-link{
  color: #409eff;
  &:hover{
    color:$mainColor;
  }
  &-no{
  }
}
</style>
